//
//  MBBaseWebController.m
//  LiveBroadcast
//
//  Created by Maybe on 2019/2/15.
//  Copyright © 2019 moonBroadcast. All rights reserved.
//

#import "MBBaseWebController.h"
#import <WebKit/WebKit.h>

@interface MBBaseWebController ()<WKNavigationDelegate,WKUIDelegate>
/**
 重写导航栏返回按钮，用来判断webView的多次返回
 */
@property(nonatomic,strong)UIButton * backNavButton;
/**
 进度条
 */
@property (nonatomic, strong) UIProgressView *progressView;

@property(nonatomic,strong)WKWebViewConfiguration * configuration;
@property(nonatomic,strong) WKWebView * webView;
@end

@implementation MBBaseWebController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = Color_Bj;
    [self.view addSubview:self.webView];
    self.navigationItem.title = self.webNavTitle;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.backNavButton];
    [self loadRequestView];
    //监听加载进度
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    //监听导航栏title
    [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    self.webView.UIDelegate = self;
    self.webView.navigationDelegate = self;
}
- (void)loadRequestView {
    if (self.webURL.length <= 0) {
        return;
    }
    NSMutableString * muString = [NSMutableString stringWithString:self.webURL];
    //这里可能需要做验签，接口加密，拼接参数等等
    NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:muString] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
    [self.webView loadRequest:request];
}
#pragma -
#pragma mark - KVC and KVO
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([@"estimatedProgress" isEqualToString:keyPath]) {
        [self.progressView setProgress:self.webView.estimatedProgress animated:YES];
    }
    if (self.webNavTitle.length == 0) {
        if ([@"title" isEqualToString:keyPath]) {
            if (object == self.webView) {
                self.navigationItem.title = self.webView.title;
            } else {
                [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
            }
        }
    }
    if (self.progressView.progress == 0) {
        self.progressView.hidden = NO;
    }else if (self.progressView.progress == 1)
    {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            //防止正在加载时隐藏
            if (self.progressView.progress ==1) {
                self.progressView.progress = 0;
                self.progressView.hidden = YES;
            }
        });
    }
}
#pragma mark - event
-(void)back {
    if (self.webView.canGoBack == YES) {
        [self.webView goBack];
        return;
    }
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma -
#pragma mark -getter

-(WKWebView *)webView {
    if (_webView == nil) {
        WKUserContentController *userContentController = [[WKUserContentController alloc]init];
        self.configuration.userContentController = userContentController;
        WKPreferences *preferences = [WKPreferences new];
        preferences.javaScriptCanOpenWindowsAutomatically = YES;
        //        preferences.minimumFontSize = 30.0;
        self.configuration.preferences = preferences;
        _webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height - 64) configuration:self.configuration];
    }
    return _webView;
}

-(WKWebViewConfiguration *)configuration {
    if (_configuration == nil) {
        _configuration = [[WKWebViewConfiguration alloc]init];
    }
    return _configuration;
}

-(UIProgressView *)progressView {
    if (_progressView == nil) {
        CGRect  rect = CGRectZero;
        rect.size.width = [[UIScreen mainScreen]bounds].size.width;
        rect.size.height = 2;
        _progressView = [[UIProgressView alloc]initWithFrame:rect];
        _progressView.progressTintColor = Color_Red;
        
        [_progressView setProgressViewStyle:UIProgressViewStyleDefault];
        [self.view addSubview:_progressView];
    }
    return _progressView;
}
-(UIButton *)backNavButton {
    if (_backNavButton == nil) {
        //设置左上角按钮
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setImage:[UIImage imageNamed:@"fanhui"] forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:@"fanhui"] forState:UIControlStateHighlighted];
        [button addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
        [button sizeToFit];
        _backNavButton   = button;
        
    }
    return _backNavButton;
}

- (void)dealloc {
    
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.webView removeObserver:self forKeyPath:@"title"];
    self.webView = nil;
    self.webView.navigationDelegate = nil;
    self.webView.UIDelegate = nil;
    [self.webView removeFromSuperview];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
